//
//  DiscoveryViewController.swift
//  clreader
//
//  Created by colin on 2019/3/6.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh

class DiscoveryViewController: CLBaseViewController {
    
    private lazy var infoTableView = UITableView(frame: CGRect.zero, style: .plain)
    private var infoData = [JSONObject]()
    private var cellHeight = [IndexPath:CGFloat]()
    private var page = Router.defaultPage
    private var taskHandle:URLSessionTask?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        let topBar = UIView().then {
            $0.backgroundColor = UIColor.white
            
            let labelTitle = UILabel().then {
                $0.text = "发现"
                $0.textColor = UIColor(hex: "343434")
                $0.font = UIFont.systemFont(ofSize: 19.0, weight: .bold)
            }
            $0.addSubview(labelTitle)
            labelTitle.snp.makeConstraints({ (make) in
                make.left.equalToSuperview().offset(15.0)
                make.centerY.equalToSuperview()
            })
            
            // 扫码
            let buttonScan = UIButton(type: .custom).then {
                $0.setImage(UIImage(named: "icon_scan"), for: .normal)
                $0.addTarget(self, action: #selector(self.actionScan(_:)), for: .touchUpInside)
            }
            $0.addSubview(buttonScan)
            buttonScan.snp.makeConstraints({ (make) in
                make.top.bottom.equalToSuperview()
                make.right.equalToSuperview()
                make.width.equalTo(44.0)
            })
            
            // 搜索
            let buttonSearch = UIButton(type: .custom).then {
                $0.setImage(UIImage(named: "icon_search"), for: .normal)
                $0.addTarget(self, action: #selector(self.actionSearch(_:)), for: .touchUpInside)
            }
            $0.addSubview(buttonSearch)
            buttonSearch.snp.makeConstraints({ (make) in
                make.top.bottom.equalToSuperview()
                make.right.equalTo(buttonScan.snp.left)
                make.width.equalTo(44.0)
            })
            
        }
        self.view.addSubview(topBar)
        topBar.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(44.0)
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
        }
        
        self.view.insertSubview(self.infoTableView, at: 0)
        self.infoTableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        self.infoTableView.do {
            $0.backgroundColor = UIColor.white
            $0.contentInset = UIEdgeInsets(top: 44.0, left: 0, bottom: 0, right: 0)
            $0.separatorStyle = .none
            $0.contentInsetAdjustmentBehavior = .never
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.estimatedRowHeight = 0
            $0.register(Cell.self, forCellReuseIdentifier: Cell.reuserId)
            $0.dataSource = self
            $0.delegate = self
            $0.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.refresh()
            })
            $0.mj_header.beginRefreshing()
        }
    }
    
}

extension DiscoveryViewController {
    private func refresh() {
        
        self.page = Router.defaultPage
        self.taskHandle?.cancel()
        self.infoTableView.mj_footer = nil
        
        self.taskHandle = Router.recommend(pageNum: self.page, pageSize: Router.defaultPageSize, type: 4).request { [weak self] (response:RequestResponse<JSONObject>) in
            
            self?.infoTableView.mj_header.endRefreshing()
            self?.taskHandle = nil
            
            if case .success(let successData,_) = response {
                if let datas = successData?["rows"] as? [JSONObject] {
                    self?.infoData = datas
                    if datas.count >= Router.defaultPageSize {
                        self?.infoTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
                            self?.loadMore()
                        })
                    }
                    
                } else {
                    self?.infoData = []
                }
                
                self?.page += 1
                self?.infoTableView.reloadData()
            }
            if case .failure(_,let message) = response {
                self?.hud.showText(message)
            }
        }
    }
    
    private func loadMore() {
        if self.taskHandle != nil {
            return
        } else {
            self.taskHandle = Router.recommend(pageNum: self.page, pageSize: Router.defaultPageSize, type: 4).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                
                if case .success(let successData,_) = response {
                    if let datas = successData?["rows"] as? [JSONObject] {
                        self?.infoData += datas
                        if datas.count >= Router.defaultPageSize {
                            self?.infoTableView.mj_footer?.endRefreshing()
                        } else {
                            self?.infoTableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                    } else {
                        self?.infoTableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                    
                    self?.page += 1
                    self?.infoTableView.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.hud.showText(message)
                    self?.infoTableView.mj_footer?.endRefreshing()
                }
            }
        }
    }
    
}

extension DiscoveryViewController {
    
    @objc private func actionSearch(_ sender:Any) {
        let controller = SearchViewController()
        controller.hidesBottomBarWhenPushed = true
        self.show(controller, sender: nil)
    }
    
    @objc private func actionScan(_ sender:Any) {
        print("scan")
    }
    
}


extension DiscoveryViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.infoData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuserId) as! Cell
        cell.refresh(data: self.infoData[indexPath.row])
        self.cellHeight[indexPath] = cell.cellHeight
        return cell
    }
}

extension DiscoveryViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height = self.cellHeight[indexPath] {
            return height
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let goods_id = self.infoData[indexPath.row]["goods_id"] as? Int {
            let controller = DiscoveryDetailViewController(goodsId: goods_id)
            self.show(controller, sender: nil)
        }
    }
}

extension DiscoveryViewController {
    class Cell : UITableViewCell {
        
        var cellHeight:CGFloat = 0
        static let reuserId = "Cell"
        
        private lazy var imageViewPhoto = UIImageView()
        private lazy var labelTitle = UILabel()
        private lazy var viewGoodsContainer = UIView()
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            
            self.selectionStyle = .none
            
            let content = CLTouchableView().then {
                $0.backgroundColor = UIColor.white
                $0.layer.shadowColor = UIColor.lightGray.cgColor
                $0.layer.shadowOffset = CGSize(width:2.0,height:2.0)
                $0.layer.shadowOpacity = 0.3
                
                $0.addSubview(self.imageViewPhoto)
                self.imageViewPhoto.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview().offset(10.0)
                    make.top.equalToSuperview().offset(10.0)
                    make.right.equalToSuperview().offset(-10.0)
                    let width = UIScreen.main.bounds.width - 50.0
                    make.height.equalTo(120.0 * (width / 325.0))
                })
                
                let imageViewMask = UIImageView(image: UIImage(named: "dis_cell_mask"))
                imageViewMask.alpha = 0.5
                $0.addSubview(imageViewMask)
                imageViewMask.snp.makeConstraints({ (make) in
                    make.edges.equalTo(self.imageViewPhoto)
                })
                
                self.labelTitle.do {
                    $0.textColor = UIColor.white
                    $0.font = UIFont.systemFont(ofSize: 17.0, weight:.light)
                }
                $0.addSubview(self.labelTitle)
                self.labelTitle.snp.makeConstraints({ (make) in
                    make.center.equalTo(self.imageViewPhoto.snp.center)
                })
                
                let lineLeft = UIView().then {
                    $0.backgroundColor = UIColor.white
                }
                $0.addSubview(lineLeft)
                lineLeft.snp.makeConstraints({ (make) in
                    make.size.equalTo(CGSize(width: 25.0, height: 1.0))
                    make.right.equalTo(self.labelTitle.snp.left).offset(-5.0)
                    make.centerY.equalTo(self.labelTitle.snp.centerY)
                })
                
                let lineRight = UIView().then {
                    $0.backgroundColor = UIColor.white
                }
                $0.addSubview(lineRight)
                lineRight.snp.makeConstraints({ (make) in
                    make.size.equalTo(CGSize(width: 25.0, height: 1.0))
                    make.left.equalTo(self.labelTitle.snp.right).offset(5.0)
                    make.centerY.equalTo(self.labelTitle.snp.centerY)
                })
                
                $0.addSubview(self.viewGoodsContainer)
                self.viewGoodsContainer.snp.makeConstraints({ (make) in
                    make.top.equalTo(self.imageViewPhoto.snp.bottom).offset(15.0)
                    make.left.equalToSuperview().offset(10.0)
                    make.right.equalToSuperview().offset(-10.0)
                })
                
            }
            self.contentView.addSubview(content)
            content.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15.0)
                make.right.equalToSuperview().offset(-15.0)
                make.top.equalToSuperview().offset(10.0)
                make.bottom.equalToSuperview()
            }
        }
        
        func refresh(data:JSONObject?) {
            
            self.cellHeight = 10.0 + 10.0
            let width = UIScreen.main.bounds.width - 50.0
            self.cellHeight += 120.0 * (width / 325.0)
            self.cellHeight += 15.0
            
            // 图片
            if let cover_url = data?["cover_url"] as? String,!cover_url.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let imageUrl = baseUrl.appendingPathComponent(cover_url)
                self.imageViewPhoto.kf.setImage(with: imageUrl)
            } else {
                self.imageViewPhoto.image = nil
            }
            
            self.labelTitle.text = data?["title"] as? String
            
            //goodsList
            for subview in self.viewGoodsContainer.subviews {
                subview.removeFromSuperview()
            }
            
            if let goodsList = data?["goodsList"] as? [JSONObject],!goodsList.isEmpty {
                
                let distance:CGFloat = 10.0
                var pre:UIView?
                
                let font = UIFont.systemFont(ofSize: 13.0, weight:.light)
                
                self.cellHeight += font.lineHeight * CGFloat(goodsList.count) + distance * CGFloat(goodsList.count)
                
                for index in 0 ..< goodsList.count {
                    let goods = goodsList[index]
                    
                    let labelGoods = UILabel().then {
                        $0.textColor = UIColor(hex: "343434")
                        $0.font = font
                        
                        var text = ""
                        if let title = goods["title"] as? String,!title.isEmpty {
                            text += title
                        }
                        
                        if let type = SourceType(type: goods["type"] as? Int) {
                            text += "  " + "\(type.name)"
                        }
                        
                        if let author = goods["author"] as? String,!author.isEmpty {
                            text +=  "  " + author
                        }
                        $0.text = text
                    }
                    self.viewGoodsContainer.addSubview(labelGoods)
                    labelGoods.snp.makeConstraints { (make) in
                        
                        make.left.equalToSuperview()

                        if let pre_ = pre {
                            make.top.equalTo(pre_.snp.bottom).offset(distance)
                        } else {
                            make.top.equalToSuperview()
                        }
                        
                        if index == goodsList.count - 1 {
                            make.bottom.equalToSuperview()
                        }
                    }
                    
                    pre = labelGoods
                }
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}
